//
//  AccessSeclectViewController.m
//  QRMaster
//
//  Created by myApple on 15/4/14.
//  Copyright (c) 2015年 myApple. All rights reserved.
//

#import "AccessSeclectViewController.h"
#import "RequestNetWork.h"
#import "userPowerModel.h"
#import "Reachability.h"
#import "PromptInfoView.h"
#import "UserPowerTableViewCell.h"
#import "BulidingCardController.h"
#import "FloorCardController.h"
#import "CardPowerModel.h"
#import "FloorCardModel.h"

@interface AccessSeclectViewController ()<UITableViewDataSource,UITableViewDelegate,userPowerTableViewCellDelegate>
{
    NSMutableArray * userPowerArray;
    UITableView * userPowerTableView;
    __block  NSMutableArray * bulidingArray;//只有楼栋
    NSMutableArray * bulidingAndFloorArray;//包括楼栋和楼层
    BOOL isHaveRoom;
    BOOL isAuthen;
}

@end

@implementation AccessSeclectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isAuthen = YES;
    isHaveRoom = YES;
    userPowerArray = [[NSMutableArray alloc]init];
    bulidingArray = [[NSMutableArray alloc]init];
    bulidingAndFloorArray = [[NSMutableArray alloc]init];
    self.view.backgroundColor = RGBA(237, 238, 241, 1);
    [self LookUserPower];
    [self getUserCardPower];
    [self prepareTableView];
    self.title = NSLocalizedString(@"powerChoose", nil);
    // Do any additional setup after loading the view.
}


-(void)prepareTableView
{
    float ScreenWidth = [UIScreen mainScreen].bounds.size.width;
    float ScreenHeight = [UIScreen mainScreen].bounds.size.height;
    float x = 0;
    float y = 0;
    float width = ScreenWidth;
    float height = ScreenHeight - 64;
    userPowerTableView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStyleGrouped];
    userPowerTableView.delegate = self;
    userPowerTableView.dataSource = self;
    userPowerTableView.scrollEnabled = NO;
    [self.view addSubview:userPowerTableView];
    
}

#pragma mark ----------查看个人总控卡权限
-(void)LookUserPower
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityid forKey:@"communityId"];
    [postDict setValue:_memberid forKey:@"memberId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(USERPOWER3) params:postDict block:^(id downLoadData, id error)
    {
        [self stopWaiting];
        NSArray * data = [downLoadData objectForKey:@"data"];
        if (downLoadData) {
            for (NSDictionary * dict in data) {
                if ([[dict objectForKey:@"authorityid"]integerValue] == 38) {
                    userPowerModel * model = [[userPowerModel alloc]init];
                    model.powerId = [dict objectForKey:@"powerid"];
                    model.authorityId = [dict objectForKey:@"authorityid"];
                    model.stutas = [dict objectForKey:@"status"];
                    model.powerName = [dict objectForKey:@"name"];
                    [userPowerArray insertObject:model atIndex:0];
                }
            }
        }
        else
        {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];
        }
        [userPowerTableView reloadData];
    }];
    
}

#pragma mark -----------获取楼栋，楼层卡权限
-(void)getUserCardPower
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityid forKey:@"communityId"];
    [postDict setValue:_memberid forKey:@"userId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(USERPOWER) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if (downLoadData) {
             NSDictionary * data = [downLoadData objectForKey:@"data"];
             NSArray * bulidAndFloorArray = [data objectForKey:@"buildingFloor"];
             if (bulidAndFloorArray.count >0) {
                 //楼栋
                 userPowerModel * bulidModel = [[userPowerModel alloc]init];
                 bulidModel.powerName = NSLocalizedString(@"buildCard", nil);
                 userPowerModel * floorModel = [[userPowerModel alloc]init];
                 floorModel.powerName = NSLocalizedString(@"floorCard", nil);
                 NSMutableString * bulidString = [[NSMutableString alloc]init];
                 NSMutableString * floorString = [[NSMutableString alloc]init];
                 for (NSDictionary * dict in bulidAndFloorArray) {
                     CardPowerModel * model = [[CardPowerModel alloc]init];
                     model.bulidingOrFloorId = [dict objectForKey:@"id"];
                     model.bulidingOrFloorName = [dict objectForKey:@"name"];
                     model.enable = [[dict objectForKey:@"enable"]boolValue];
                     [bulidingArray addObject:model];
                     if (model.enable) {
                         [bulidString appendString:[NSString stringWithFormat:@"%@,",model.bulidingOrFloorName]];
                     }
                     //楼层
                     NSArray * floorsArray = [dict objectForKey:@"floor"];
                     NSMutableArray * floorArray = [[NSMutableArray alloc]init];
                     for (NSDictionary * floorDict in floorsArray) {
                         FloorCardModel * floorCModel = [[FloorCardModel alloc]init];
                         floorCModel.floorCardId = [floorDict objectForKey:@"id"];
                         floorCModel.floorCardName = [NSString stringWithFormat:@"%@",[floorDict objectForKey:@"name"]];
                         floorCModel.enable = [[floorDict objectForKey:@"enable"]boolValue];
                         floorCModel.bulidingCardName =[dict objectForKey:@"name"];
                         [floorArray addObject:floorCModel];
                         if (floorCModel.enable) {
                             [floorString appendString:[NSString stringWithFormat:@"%@-%@,",floorCModel.bulidingCardName,floorCModel.floorCardName]];
                         }
                     }
                     [bulidingAndFloorArray addObject:floorArray];
                 }
                 if (bulidString.length > 0) {
                     bulidString = [NSMutableString stringWithString:[bulidString substringToIndex:(bulidString.length - 1)]] ;
                 }
                 bulidModel.selectName = bulidString;
                 [userPowerArray addObject:bulidModel];
                 
                 if (floorString.length > 0) {
                     floorString = [NSMutableString stringWithString:[floorString substringToIndex:(floorString.length - 1)]] ;
                 }
                 floorModel.selectName = floorString;
                 [userPowerArray addObject:floorModel];
             }
             else if(bulidAndFloorArray.count == 0)
             {
                 userPowerModel * bulidModel = [[userPowerModel alloc]init];
                 bulidModel.powerName = NSLocalizedString(@"buildCard", nil);
                 userPowerModel * floorModel = [[userPowerModel alloc]init];
                 floorModel.powerName = NSLocalizedString(@"floorCard", nil);
                 [userPowerArray addObject:bulidModel];
                 [userPowerArray addObject:floorModel];
                 isHaveRoom = NO;
             }

         }
         else if(error != nil)
         {
             if ([[error objectForKey:@"status"]integerValue] == 303) {
                 userPowerModel * bulidModel = [[userPowerModel alloc]init];
                 bulidModel.powerName = NSLocalizedString(@"buildCard", nil);
                 userPowerModel * floorModel = [[userPowerModel alloc]init];
                 floorModel.powerName = NSLocalizedString(@"floorCard", nil);
                 [userPowerArray addObject:bulidModel];
                 [userPowerArray addObject:floorModel];
                 isAuthen = NO;
             }
             else
             {
                 [PromptInfoView showMessage:[error objectForKey:@"info"]];
             }
         }
         [userPowerTableView reloadData];
     }];
}

#pragma mark -----------delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return userPowerArray.count;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return NSLocalizedString(@"cardPower", nil);
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 39.0;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * cellId = @"cell";
    UserPowerTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[UserPowerTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    cell.delegate = self;
    if (userPowerArray.count > indexPath.row) {
        userPowerModel * model = userPowerArray[indexPath.row];
        if (indexPath.row == 0) {
            cell.powerId = model.powerId;
            cell.powerName = model.powerName;
            cell.authorityId = model.authorityId;
            cell.stutas = model.stutas;
            cell.showNextImage = NO;
        }
        else
        {
            cell.powerName = model.powerName;
            cell.selectedName = model.selectName;
            cell.showNextImage = YES;
        }
       
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        return;
    }
    if (!isHaveRoom) {
        [PromptInfoView showMessage:NSLocalizedString(@"noRoomForPowerCard", nil)];
        return;
    }
    if (!isAuthen) {
        [PromptInfoView showMessage:NSLocalizedString(@"noAuthForCommunity", nil)];
        return;
    }
    if (indexPath.row == 1) {
        BulidingCardController * bcc = [[BulidingCardController alloc]init];
        bcc.bulidingArray = bulidingArray;
        bcc.userId = _memberid;
        bcc.block = ^(NSString * bulidingIdString)
        {
            NSMutableString * bulidingString = [[NSMutableString alloc]init];
            userPowerModel * powerModel = userPowerArray[indexPath.row];
             NSArray * idArray = [bulidingIdString componentsSeparatedByString:@","];
            for (NSInteger i = 0 ; i < bulidingArray.count; i++) {
                CardPowerModel * model = bulidingArray[i];
                model.enable = NO;
                for (NSString * idString in idArray) {
                    if ([idString isEqualToString:model.bulidingOrFloorId]) {
                        model.enable = YES;
                        [bulidingString  appendString:[NSString stringWithFormat:@"%@,",model.bulidingOrFloorName]];
                        break;
                    }
                }
                [bulidingArray replaceObjectAtIndex:i withObject:model];
            }
            if (bulidingString.length >0) {
                bulidingString = [NSMutableString stringWithString:[bulidingString substringToIndex:(bulidingString.length - 1)]];
            }
            powerModel.selectName = bulidingString;
            [userPowerArray replaceObjectAtIndex:indexPath.row withObject:powerModel];
            [userPowerTableView reloadData];
        };
        [self.navigationController pushViewController:bcc animated:YES];
    }
    else if (indexPath.row == 2)
    {
        FloorCardController * fcc = [[FloorCardController alloc]init];
        fcc.floorArray = bulidingAndFloorArray;
        fcc.userId = _memberid;
        fcc.IDBlock = ^(NSString * floorId)
        {
            NSMutableString * floorString = [[NSMutableString alloc]init];
            userPowerModel * powerModel = userPowerArray[indexPath.row];
            NSArray * idArray = [floorId componentsSeparatedByString:@","];
            for (NSMutableArray * floorArray in bulidingAndFloorArray) {
                for (NSInteger i = 0 ; i < floorArray.count; i ++) {
                    FloorCardModel * model = floorArray[i];
                    model.enable = NO;
                    for (NSString * floorCardId in idArray) {
                        if ([floorCardId isEqualToString:model.floorCardId]) {
                            model.enable = YES;
                            [floorString appendString:[NSString stringWithFormat:@"%@-%@,",model.bulidingCardName,model.floorCardName]];
                            break;
                        }
                    }
                    [floorArray replaceObjectAtIndex:i withObject:model];
                }
            }
            if (floorString.length >0) {
                floorString = [NSMutableString stringWithString:[floorString substringToIndex:(floorString.length - 1)]];
            }
            powerModel.selectName = floorString;
            [userPowerArray replaceObjectAtIndex:indexPath.row withObject:powerModel];
            [userPowerTableView reloadData];
        };
        [self.navigationController pushViewController:fcc animated:YES];
    }
}


#pragma mark --------- 修改总控卡权限
-(void)saveMemeberRoom:(NSMutableArray *)array
{
    if ([self IsHaveNetwork]) {
        return;
    }
    NSString * json = nil;
    if ([NSJSONSerialization isValidJSONObject:array]) {
        NSError *error;
        NSData * jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
        json = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:_communityid forKey:@"communityId"];
    [postDict setValue:_memberid forKey:@"memberId"];
    [postDict setValue:json forKey:@"parameter"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(NEWPOSTUSERPOWER) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
         if (downLoadData) {
             [PromptInfoView showMessage:NSLocalizedString(@"modifyPowerSuccess", nil) superView:self.view];
         }
         else
         {
            [PromptInfoView showMessage:[error objectForKey:@"info"]];

         }
     }];
}

#pragma mark -- userpowertableviewcelldelegate
-(void)userPowerCellSendDict:(NSMutableArray *)array
{
    [self saveMemeberRoom:array];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
